package webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	private InputStream in;
	private PrintStream out;
	private String workSpace;
	
	public Processor(Socket socket,String workSpace) {
		try {
			this.workSpace = workSpace;
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		String filename = this.parse(in);
		this.sendFile(filename);
	}
	
	private String parse(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String filename = null;
		try {
			String httpMessage = br.readLine();
			String[] content = httpMessage.split(" ");
			if(content.length != 3) {
				this.sendErrorMessage(404, "Client query error!");
				return null;
			}
			filename = content[1];
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}
	
	public void sendErrorMessage(int errorCode,String errorMessage) {
		out.println("HTTP/1.0 "+errorCode+" "+errorMessage);
		out.println("content-type: text/html");
		out.println();
		StringBuffer sb = new StringBuffer();
		sb.append("<thml>");
		sb.append("<title>Error Message</title>");
		sb.append("<body>");
		sb.append("<h1>ErrorCode:"+errorCode+",Message"+errorMessage+"</h1>");
		sb.append("</body></thml>");
		out.println(sb);
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void sendFile(String filename) {
		File file = new File(this.workSpace + filename);
		if(!file.exists()) {
			this.sendErrorMessage(404, "File Not Found!");
		}
		try {
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int)file.length()];
			in.read(content);
			StringBuffer sb = new StringBuffer();
			sb.append("HTTP/1.0 200 send queryfile");
			sb.append("content-length\"+content.length");
			out.println(sb);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
